package sdk.common;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import sdk.garena.SDKConstants;
import sun.misc.BASE64Encoder;

/**
 * 加密类
 * 
 * @author hexuhui
 * 
 */
public class CryptoUtils {

	private static final String HmacSHA256 = "HmacSHA256";

	private static CryptoUtils instance;

	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
			'e', 'f' };

	private Mac hmacSha256;

	private Mac hmacSha256Post;

	public static CryptoUtils getInstance() {
		if (instance == null) {
			instance = new CryptoUtils();
		}
		return instance;
	}

	public CryptoUtils() {
		SecretKey secretKey = new SecretKeySpec(SDKConstants.GARENA_PAYMENT_KEY.getBytes(), HmacSHA256);
		try {
			hmacSha256 = Mac.getInstance(HmacSHA256);
			hmacSha256.init(secretKey);
		} catch (Exception e) {
			e.printStackTrace();
		}

		SecretKey secretKeyPost = new SecretKeySpec(SDKConstants.GARENA_POST_KEY.getBytes(), HmacSHA256);
		try {
			hmacSha256Post = Mac.getInstance(HmacSHA256);
			hmacSha256Post.init(secretKeyPost);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String hmacSha256ToHex(String queryStr) throws IllegalStateException, UnsupportedEncodingException {
		byte[] resultStr = hmacSha256.doFinal(queryStr.getBytes("UTF-8"));
		return Hex.encodeHexString(resultStr);
	}

	public String hmacSha256ToHexForPost(String queryStr) throws IllegalStateException, UnsupportedEncodingException {
		byte[] resultStr = hmacSha256Post.doFinal(queryStr.getBytes("UTF-8"));
		return Hex.encodeHexString(resultStr);
	}

	public String sha1(String queryStr) {
		if (queryStr == null) {
			return null;
		}
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
			messageDigest.update(queryStr.getBytes());
			return getFormattedText(messageDigest.digest());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private String getFormattedText(byte[] bytes) {
		int len = bytes.length;
		StringBuilder buf = new StringBuilder(len * 2);
		// 把密文转换成十六进制的字符串形式
		for (int j = 0; j < len; j++) {
			buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
			buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
		}
		return buf.toString();
	}

	public String encoderMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		// 确定计算方法
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		BASE64Encoder base64en = new BASE64Encoder();
		// 加密后的字符串
		String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));
		return newstr;
	}

	public static void main(String[] args) {
		String retStr = DigestUtils.md5Hex("tangfuqiang");
		System.out.println(retStr);
	}

}
